using System.Collections.Generic;
using JKFrame;
using UnityEngine;

namespace Map.config
{
    public class MapChunkData
    {
        public List<MapChunkObjectModel> MapChunkObjectModels = new List<MapChunkObjectModel>();
    }

    public class MapChunkObjectModel
    {
        public GameObject Prefab;
        public Vector3 Position;
    }

    public class MapChunkController : MonoBehaviour
    {
        public Vector2Int ChunkIndex { get; private set; }

        public Vector3 CenterPosition { get; private set; }
        private bool isActive = false;
        private MapChunkData mapChunkData;
        private List<GameObject> mapChunkObjects = new List<GameObject>();

        public void Init(Vector2Int index, Vector3 centerPosition, List<MapChunkObjectModel> MapChunkObjects)
        {
            this.ChunkIndex = index;
            this.CenterPosition = centerPosition;
            mapChunkData = new MapChunkData();
            mapChunkData.MapChunkObjectModels = MapChunkObjects;
        }

        public void SetActive(bool isActive)
        {
            if (isActive != this.isActive)
            {
                this.isActive = isActive;
                gameObject.SetActive(this.isActive);

                //TODO:基于对象池生成所有的地图对象 花、草、树、石头等
                if (this.isActive)
                {
                    foreach (var item in mapChunkData.MapChunkObjectModels)
                    {
                        GameObject gameObject = PoolSystem.GetGameObject(item.Prefab.name, transform);
                        if (gameObject == null)
                        {
                            gameObject = Instantiate(item.Prefab, transform);
                        }

                        gameObject.transform.position = item.Position;
                        mapChunkObjects.Add(gameObject);
                    }
                }
                else
                {
                    for (int i = 0; i < mapChunkData.MapChunkObjectModels.Count; i++)
                    {
                        PoolSystem.PushGameObject(mapChunkData.MapChunkObjectModels[i].Prefab.name, mapChunkObjects[i]);
                    }

                    mapChunkObjects.Clear();
                }
            }
        }
    }
}